package com.qianniu.napi.admin.web;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.Account;
import com.qianniu.napi.admin.entity.AccountFlow;
import com.qianniu.napi.admin.entity.Jinfo;
import com.qianniu.napi.admin.entity.User;
import com.qianniu.napi.admin.entity.penum.GtypeEnum;
import com.qianniu.napi.admin.entity.penum.IotypeEnum;
import com.qianniu.napi.admin.entity.penum.XftypeEnum;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.util.ObjectUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 个人账务表
 * </p>
 *
 * @author chenxuebin
 * @since 2018-07-07
 */
@Controller
public class AccountController {

    private static final Logger logger = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private IUserService userService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IMaccountService maccountService;
    @Autowired
    private IAccountFlowService accountflowService;
    @Autowired
    private IFensService fensService;
    @Autowired
    private IJifenService jifenService;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private IRedisService redisService;

    @Autowired
    private IQnpay qnpay;

    @RequiresPermissions("admin:user:view")
    @RequestMapping("admin/account/index")
    public String index() {
        return "admin/account";
    }

    @RequiresPermissions("admin:user:view")
    @RequestMapping("/admin/account/list")
    @ResponseBody
    public Page<Account> alist(@RequestParam(value = "limit", required = false) int limit,
                               @RequestParam(value = "search", required = false) String search,
                               @RequestParam(value = "offset", required = false) int offset) {
        User user = ObjectUtil.getSessionUser();
        Wrapper<Account> wrapper = new EntityWrapper<Account>();
        int utype = ObjectUtil.getUserType();
        if (utype <= 39)
            wrapper.eq("mpid", ObjectUtil.getMpid());
        else if (utype < 99)
            wrapper.eq("mid", ObjectUtil.getMid());
        if(!Strings.isNullOrEmpty(search))
            wrapper.and().eq("phone",search);


        wrapper.orderBy("id", true);
        Page<Account> page = accountService.selectPage(new Page<Account>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/account/add")
    public String add(@Valid Account bean, BindingResult bindingResult) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setCreatetime(new Date());
        bean.setMid(ObjectUtil.getMid());
        bean.setUid(ObjectUtil.getUid());
        bean.insert();
        return "admin/account";
    }

    @RequestMapping("/admin/account/getAccountById")
    @ResponseBody
    public Account getAccountById(long id) {
        Account bean = accountService.selectById(id);
        return bean;
    }

    @RequestMapping("/admin/account/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = accountService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/account/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        Account bean = new Account();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        accountService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/account/modify")
    public String update(Account bean) {
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        boolean isSuccc = accountService.updateById(bean);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

    @RequestMapping("/admin/account/chongzhi")
    public String chongzhi(int money, Long uid) {

        AccountFlow af = new AccountFlow();

        af.setRemark("管理给会员用户充值");
        af.setTradetime(new Date());
        af.setState(1);
        af.setMid(ObjectUtil.getMid());
        af.setMpid(ObjectUtil.getMpid());
        af.setUid(uid);
        af.setCreatetime(new Date());
        BigDecimal zero = new BigDecimal(0);
        af.setTotal(BigDecimal.valueOf(money));
        af.setRealpay(zero);
        af.setAmount(BigDecimal.valueOf(money));
        af.setDikou(zero);

        User user = userService.selectById(uid);

        af.setNickname(user.getNickName());
        af.setPhone(user.getPhone());
        af.setHeadimg(user.getAvatarPic());

        af.setIsConfirm(-1);//线下支付
        af.setState(-1);//线下支付
        af.setIotype(IotypeEnum.input.getVal());
        af.setXftype(XftypeEnum.recharge.getVal());//线下付款买单

        boolean flag = false;
        int cout = 0;
        Account naccount = new Account();
        Account act = new Account();
        // 处理消费流水（消费+买单+转账）
        // 消费(累计消费变化)
        while (af != null && !flag) {
            cout++;
            act = accountService.selectOne(new EntityWrapper<Account>().eq("uid", uid));
            if (act == null) {
                break;
            }

            Long version = act.getVersion();

            BigDecimal total = act.getTotal();
            BigDecimal amount = act.getAmount();
            BigDecimal chargeAmount = act.getChargeAmount();

            // 用户在线购物+用户自助买单+用户线下扫码支付
            naccount.setTotal(total.add(af.getAmount()));
            naccount.setAmount(amount.add(af.getAmount()));
            naccount.setChargeAmount(chargeAmount.add(af.getAmount()));

            naccount.setModifytime(new Date());
            naccount.setModifier(uid);
            naccount.setVersion(version + 1);

            af.setState(1);
            af.setIsConfirm(1);//线下支付
            af.setLasttotal(act.getTotal());//线下支付
            af.setConfirmDate(new Date());

            flag = accountService.update(naccount, new EntityWrapper<Account>().eq("uid", uid).eq("version", version));
            logger.info("===========Account flag=" + flag + " and cout=" + cout);
            if (flag) {
                af.insertOrUpdate();
                break;
            }
        }

        return "redirect:index";
    }

    /// / ************* bellow is bean interface for user *********

    private Account initAccount() {

        BigDecimal zero = new BigDecimal(0);
        Account bean = new Account();

        bean.setTotal(zero);
        bean.setAmount(zero);
        bean.setUnuseAmount(zero);
        bean.setFanli(zero);
        bean.setFanliing(zero);
        bean.setFreeze(zero);
        bean.setChargeAmount(zero);
        bean.setWithdraw(zero);
        bean.setMamount(zero);

        bean.setState(1);
        bean.setUid(ObjectUtil.getUid());
        bean.setMid(ObjectUtil.getMid());
        bean.setMpid(ObjectUtil.getMpid());
        bean.setPhone("");
        bean.setVersion(0l);
        bean.setCreatetime(new Date());
        logger.info(">>>>>>>>>>>initAccount user=", JSON.toJSONString(bean));
        bean.insert();

        return bean;
    }

    @RequestMapping("/test/account/setuinfo")
    @ResponseBody
    public Jinfo setuinfo(String uix) {
        if (Strings.isNullOrEmpty(uix)) return null;

        List<Account> aflist = accountService.selectList(new EntityWrapper<Account>().eq("mpid", uix));
        List<User> ulist = userService.selectList(new EntityWrapper<User>().eq("mpid", uix));
        Map<String, User> umap = new HashMap<String, User>();
        for (User item : ulist) {
            umap.put("user" + item.getId().toString(), item);
        }
        int skip = 0;
        for (Account item : aflist) {
            skip++;
            if (item.getNickname() != null && item.getHeadimg() != null) continue;
            if (umap.get("user" + item.getUid().toString()) == null) {
                logger.info("===================================skip=" + skip);
                continue;
            }

            item.setNickname(umap.get("user" + item.getUid().toString()).getNickName());
            item.setHeadimg(umap.get("user" + item.getUid().toString()).getAvatarPic());
            item.setPhone(umap.get("user" + item.getUid().toString()).getPhone());
            item.updateAllColumnById();
        }

        return new Jinfo();
    }

}
